package com.zonda.study.opengl.image;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * Created by zhuqiuzhu on 17/3/24.
 * GL 图片渲染器
 */

public class ImageRenderer implements GLSurfaceView.Renderer {

    private final Context mContext;

    private StationLogo mStationLogo;
    private ShaderProgram mStationLogoProgram;

    private int mStationLogoTexture;

    private final float[] projectionMatrix = new float[16];

    public ImageRenderer(Context context) {
        mContext = context;
    }

    @Override
    public void onSurfaceCreated(GL10 glUnUsed, EGLConfig config) {

        GLES20.glClearColor(1.0f, 0.5f, 0.5f, 1f);

        mStationLogo = new StationLogo();
        mStationLogoProgram = new ShaderProgram(
                mContext,
                R.raw.texture_vertex_shader,
                R.raw.texture_fragment_shader);

        mStationLogoTexture = TextureHelper.loadTexture(mContext, R.drawable.logo_16x9);
    }

    @Override
    public void onSurfaceChanged(GL10 glUnUsed, int width, int height) {

        GLES20.glViewport(0, 0, width, height);

        Log.i("TAG", "width: " + width + " height: " + height);

//        final float aspectRatio = width > height ?
//                (float) width / (float) height :
//                (float) height / (float) width;
//
//        if (width > height) {
//            // Landscape
//            Matrix.orthoM(projectionMatrix, 0, -aspectRatio, aspectRatio, -1f, 1f, -1f, 1f);
//        } else {
//            // Portrait or square
//            Matrix.orthoM(projectionMatrix, 0, -1f, 1f, -aspectRatio, aspectRatio, -1f, 1f);
//        }
    }

    @Override
    public void onDrawFrame(GL10 glUnUsed) {

        //清空渲染界面
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

        GLES20.glEnable(GLES20.GL_BLEND);
        GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);

        //告知 OpenGL 使用此着色器程序
        mStationLogoProgram.useProgram();

        Matrix.setIdentityM(projectionMatrix, 0);

        //传递 uniform 数据
        mStationLogoProgram.setUniform(projectionMatrix, mStationLogoTexture);
        //绑定顶点数据
        mStationLogo.bindData(mStationLogoProgram);
        //开始绘制
        mStationLogo.draw();

        GLES20.glDisable(GLES20.GL_BLEND);
    }
}
